package io.gitee.yxsnake.framework.web.config;

import io.gitee.yxsnake.framework.web.config.properties.XssProperties;
import io.gitee.yxsnake.framework.web.filter.TraceFilter;
import io.gitee.yxsnake.framework.web.filter.XssFilter;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * @author snake
 * @description Filter配置
 * @since 2024/11/2 22:20
 */
@AutoConfiguration
@EnableConfigurationProperties(XssProperties.class)
public class FilterConfig {

    @Bean
    @ConditionalOnProperty(value = "track.enabled", havingValue = "true",matchIfMissing = true)
    public FilterRegistrationBean<TraceFilter> mdcFilterRegistration() {
        FilterRegistrationBean<TraceFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST,DispatcherType.FORWARD,DispatcherType.ASYNC,DispatcherType.INCLUDE,DispatcherType.ERROR);
        registration.setFilter(new TraceFilter());
        registration.addUrlPatterns("/*");
        registration.setName("traceFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 1);
        return registration;
    }


    @Bean
    @ConditionalOnProperty(value = "xss.enabled", havingValue = "true",matchIfMissing = true)
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 2);
        return registration;
    }

}
